#coding=utf-8
# python版pdf转Markdown
# https://www.jb51.net/article/202636.htm
# https://cloud.tencent.com/developer/article/1943134
# https://blog.csdn.net/wujizhishui/article/details/120282944

# 第一步，mammoth 将 Word 文档转换为 HTML
# 第二步，markdownify 将 HTML 文档转换为 Markdown 文档
# pip install mammoth
# pip install markdownify

import mammoth
# stderr:TypeError: 'module' object is not callable
# import markdownify
# https://vimsky.com/examples/usage/how-to-convert-html-to-markdown-in-python.html
# 只import需要如此调用：markdownify.markdownify(html, heading_style="ATX")
from markdownify import markdownify
import os
import time
from sys import argv
from pathlib import Path

# 将Docx转变为HTML
# 支持word中存在图片
# 命令行：mammoth input_name.docx output_name.html
def wordToHtml(filename):
    with open(filename+".docx", "rb") as docx_file:
        result = mammoth.convert_to_html(docx_file)
        with open(filename+".html", "w") as html_file:
            html_file.write(result.value)

# 将Docx转变为MD
# 不支持word中存在图片
# 命令行：mammoth input_name.docx output.md --output-format=markdown
def wordToMd(filename):
    with open(filename+".docx", "rb") as docx_file:
        result = mammoth.convert_to_markdown(docx_file)
        with open(filename+".md", "w") as markdown_file:
            markdown_file.write(result.value)

# 支持word中有图片转为MD
# 转存Word文档内的图片
def convert_img(image):
  with image.open() as image_bytes:
    file_suffix = image.content_type.split("/")[1]
    # word中图片转为的目录,如果不存在则新建
    my_img = Path("./img")
    if my_img.is_dir()==0:
        os.makedirs("img")
    path_file = "./img/{}.{}".format(str(time.time()),file_suffix)
    with open(path_file, 'wb') as f:
      f.write(image_bytes.read())
  return {"src":path_file}

# 读取Word文件
def MD(filename):
    # with open(r"F:\自媒体\Python爬虫实战与机器学习应用.docx" ,"rb") as docx_file:
    # 报错1：print(md)：UnicodeEncodeError: 'gbk' codec can't encode character '\u2022' in position 12255: illegal multibyte sequence
    # https://blog.csdn.net/weixin_42421850/article/details/94389565
    # 在windows中，新建的文本文件的默认编码是gbk，所以指定编码：with open(‘test.html’, ‘w’, encoding=‘utf-8’)as f:
    # 报错2：stderr:ValueError: binary mode doesn't take an encoding argument
    # https://blog.csdn.net/qq_41475067/article/details/115733259
    # mode = "rb"时，rb+操作时不支持指定encoding参数，直接注释掉 print(md)
    # with open(filename+".docx", "rb",encoding='utf-8') as docx_file:
    with open(filename+".docx", "rb") as docx_file:
        # 转化Word文档为HTML
        result = mammoth.convert_to_html(docx_file,convert_image=mammoth.images.img_element(convert_img))
        # 获取HTML内容
        html = result.value
        # 转化HTML为Markdown
        md = markdownify(html,heading_style="ATX")
        #print(md)
        with open("./docx_to_html.html",'w',encoding='utf-8') as html_file,open("./docx_to_md.md","w",encoding='utf-8') as md_file:
            html_file.write(html)
            md_file.write(md)
        messages = result.messages

if __name__ == '__main__':
    print('------------------------begin---------------------------')
    docx_filename = argv[1]
    MD(docx_filename)
    print('-------------------------end----------------------------')
